package com.example.demo.generator.scaffold.service;

import com.example.demo.generator.scaffold.catalog.TemplateCatalog;
import com.example.demo.generator.scaffold.catalog.TemplateCategory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class TemplateCatalogService {

    private static final String CATALOG_PATH = "scaffold/templates/template.json";

    private final ObjectMapper objectMapper = new ObjectMapper();
    private TemplateCatalog catalog;

    @PostConstruct
    public void loadCatalog() {
        ClassPathResource resource = new ClassPathResource(CATALOG_PATH);
        try (InputStream inputStream = resource.getInputStream()) {
            this.catalog = objectMapper.readValue(inputStream, TemplateCatalog.class);
        } catch (IOException ex) {
            throw new IllegalStateException("无法加载模板目录: " + CATALOG_PATH, ex);
        }
    }

    public List<TemplateCategory> getCategories() {
        if (catalog == null) {
            return Collections.emptyList();
        }
        return catalog.getCategories();
    }

    public Optional<TemplateCategory> getCategory(String id) {
        if (catalog == null) {
            return Optional.empty();
        }
        return catalog.getCategories().stream()
                .filter(category -> category.getId().equals(id))
                .findFirst();
    }
}
